package com.jintoufs.web.action.sys;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.domain.common.xEditableItem;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.domain.user.User;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.role.RoleService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.service.user.PasswordHelper;
import com.jintoufs.service.user.UserService;
import com.jintoufs.util.ztree.TreeNode;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by zhx
 */
@Controller
@Scope("prototype")
@RequestMapping("/user")
public class UserAction extends SupportAction {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private DictionaryService dictionaryService;
    @Autowired
    private PasswordHelper passwordHelper;
    @Resource
    private CustomerService customerService;

    @RequestMapping("/list")
    public String list() {
        return "user/list";
    }

    @RequestMapping("/oper")
    @SystemControllerLog(description = "用户")
    public void oper(HttpServletResponse response, String _id, String oper, User user, String photo) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            if (oper.equals("del") && _id != null) {
                String[] ids = _id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    userService.delete(Integer.parseInt(ids[i]));
                }
            } else {

                if (oper.equals("edit")) {
                    userService.update(user);
                    ajaxMsg.setCode("200");
                    ajaxMsg.setMessage("更新成功");
                } else if (oper.equals("add")) {
                    user.setPassword(Constants.USER_DEFAULT_PASSWORD);
                    user.setModified(Constants.USER_PASSWORD_NOT_MODIFY);
                    user.setCreateTime(new Date());
                    User tmp = userService.add(user);
                    if (tmp == null) {
                        ajaxMsg.setCode("500");
                        ajaxMsg.setMessage("添加失败，用户名重复");
                    } else {
                        ajaxMsg.setCode("200");
                        ajaxMsg.setMessage("添加成功");
                    }
                } else {
                    ajaxMsg.setCode("500");
                    ajaxMsg.setMessage("操作代码错误！系统只提供增加/修改/删除功能。");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode("500");
            if (e instanceof DuplicateKeyException) {
                ajaxMsg.setMessage("此员工编号已存在！");
            } else {
                ajaxMsg.setMessage("程序出错，请联系管理员！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    @RequestMapping("/delete")
    @SystemControllerLog(description = "删除用户")
    public void delete(HttpServletResponse response, Integer id) {
        userService.delete(id);
        writeInfo(response, JSON.toJSONString(new AjaxMsg()));
    }

    /**
     * input.do?id= 进入类目编辑页面 <br>
     * input.do 进入类目新增页面（不包含选中父类目）
     *
     * @param id    类目Id
     * @param model
     * @return vm/category/input.vm
     */
    @RequestMapping("input")
    public String input(Integer id, Model model) {
        Map<String, Object> result = Maps.newHashMap();
        String title;

        // 是否为编辑保存
        String isEdit;

        // 修改
        if (id != null && id != 0) {
            title = "修改用户";
            result = userService.queryUserById(id);

            isEdit = "edit";
        } else {
            title = "新增用户";
            isEdit = "add";
        }

        List<Dictionary> statusList = dictionaryService.getDicByKeyNo("员工状态");
        List<xEditableItem> itemList = new ArrayList<>();
        for (
                Dictionary dic : statusList)

        {
            xEditableItem item = new xEditableItem();
            item.setValue(dic.getKeyValue());
            item.setText(dic.getCaption());
            itemList.add(item);
        }

        String roleId = "0";

        if (result != null && result.get("roleId") != null)

        {
            roleId = result.get("roleId").toString();
        }

        // 查询所有角色
        List<TreeNode> roleList = roleService.getRoleMenu(roleId);
        model.addAttribute("roleTree", JSON.toJSONString(roleList));
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("itemList", JSON.toJSONString(itemList));
        model.addAttribute("result", result);
        model.addAttribute("title", title);

        return "user/user-detail";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map> list = userService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(), pageInfo.getList());
    }

    /**
     * 初始化用户密码
     */
    @RequestMapping("/initPassword")
    @ResponseBody
    @SystemControllerLog(description = "初始化用户密码")
    public AjaxMsg initPassword(Integer id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        if (id != null && id != 0) {
            User user = userService.initPassword(id);
        }
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }


    /**
     * 获取用户详细信息
     */
    @RequestMapping("/getDetail")
    public String getDetail(Integer id, Model model) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (id != null && id != 0) {
            result = userService.queryUserById(id);
        }
        model.addAttribute("result", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "员工的个人详细信息");
        return "user/user-detail";
    }



    @RequestMapping("/getUserByRole")
    @ResponseBody
    public List<User> getUserByRole(String roleName) {
        List<User> users = userService.getUserByRoleName(roleName);
        return users;
    }

    /**
     * 修改用户密码
     */
    @RequestMapping("/modifyPwd")
    @ResponseBody
    @SystemControllerLog(description = "修改用户密码")
    public AjaxMsg modifyPwd(String username, String newPwd) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Customer user = null;
            Map<String, Object> params = Maps.newHashMap();
            params.put("userName", username);
            List<Customer> list = customerService.queryByParams(params);
            if (list != null && list.size() > 0) {
                user = list.get(0);
            }
            if (user != null) {
                user.setPassword(newPwd);
                user.setModified((byte)1);
                passwordHelper.encryptPassword(user);
                customerService.update(user);
            }
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
            ajaxMsg.setMessage("修改密码成功！");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("修改密码失败！");
        }
        return ajaxMsg;
    }
}
